//
//  AppDelegate+HJRCIMDeleagte.m
//  project
//
//  Created by hu on 2019/3/26.
//  Copyright © 2019 健健. All rights reserved.
//

#import "AppDelegate+HJRCIMDeleagte.h"
#import <UserNotifications/UserNotifications.h>
#import "BPush.h"
#import "HJChatRoomVC.h"
#import "HJTabBarViewController.h"
#import "HJNavigationViewController.h"
#import "NSString+HJDeviceRegister.h"
#import "HJPushModel.h"

static NSString *const shareStr = @"grop.cn.rongcloud.im.share";

@implementation AppDelegate (HJRCIMDeleagte) 

#pragma mark - Configure RCIM SDK
- (void)configureUMessageWithAppKey:(NSString *)appKey launchOptions:(NSDictionary *)launchOptions application:(UIApplication *)application {
    [[RCIMClient sharedRCIMClient] initWithAppKey:appKey];// 注册融云
    [[RCIMClient sharedRCIMClient] recordLaunchOptionsEvent:launchOptions];// 融云统计
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:[[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE)]]];
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [application registerForRemoteNotifications];
                    });
                });
            }
        }];
    }
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {//c注册推送 iOS8
        UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |UIUserNotificationTypeSound) categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
     // 百度云推送服务 - debug模式
    //[BPush registerChannel:launchOptions apiKey:BaiduPushAppKey pushMode:BPushModeDevelopment withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"" useBehaviorTextInput:YES isDebug:YES];
    [BPush registerChannel:launchOptions apiKey:BaiduPushAppKey pushMode:BPushModeProduction withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"" useBehaviorTextInput:YES isDebug:NO];
    // 禁用地理位置推送 需要再绑定接口前调用。
    [BPush disableLbs];
    
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }
#if TARGET_IPHONE_SIMULATOR
    Byte dt[32] = {0xc6, 0x1e, 0x5a, 0x13, 0x2d, 0x04, 0x83, 0x82, 0x12, 0x4c, 0x26, 0xcd, 0x0c, 0x16, 0xf6, 0x7c, 0x74, 0x78, 0xb3, 0x5f, 0x6b, 0x37, 0x0a, 0x42, 0x4f, 0xe7, 0x97, 0xdc, 0x9f, 0x3a, 0x54, 0x10};
    [self application:application didRegisterForRemoteNotificationsWithDeviceToken:[NSData dataWithBytes:dt length:32]];
#endif
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //融云即时通讯
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessageNotification:) name:RCKitDispatchMessageNotification object:nil];
}

- (void)didReceiveMessageNotification:(NSNotification *)notification {
    NSNumber * left = [notification.userInfo objectForKey:@"left"];
    
    if ([RCIMClient sharedRCIMClient].sdkRunningMode == RCSDKRunningMode_Background && 0==left.integerValue) {
        int unMsgCount =[[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE)]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unMsgCount];
        });
    }
}
#pragma mark -- 注册通知用户设置
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    [application registerForRemoteNotifications];
}

#pragma mark -- 将得到DeviceToken传给BPush SDK
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
    [BPush registerDeviceToken:deviceToken];
    NSString * deviceCode = [NSString getUUIDByKeyChain];
//    NSLog(@"deviceCode = %@", deviceCode);
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 网络错误
        if (error) return;
        if (result) {
            // 确认绑定成功
            if ([result[@"error_code"]intValue]!=0) return;
            [[NSNotificationCenter defaultCenter]postNotificationName:@"PushNotification" object:nil];
            [BPush listTagsWithCompleteHandler:^(id result, NSError *error) {
            }];
            if ([HJUserManager getUserModel].userId.length) {
                [BPush delTags:@[deviceCode, [HJUserManager getUserModel].userId] withCompleteHandler:^(id result, NSError *error) {
                    NSLog(@"先删除tag 再设置");
                }];
                [BPush setTags:@[deviceCode, [HJUserManager getUserModel].userId] withCompleteHandler:^(id result, NSError *error) {
                    NSLog(@"error = %@, result = %@", error, result);
                }];
                
            }
        }
    }];
    
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"DeviceToken注册失败=%@",error.localizedDescription);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    HJPushModel *model = [HJPushModel yy_modelWithDictionary:userInfo];
    // app 杀死状态下，直接跳转到跳转页面
    if ((application.applicationState == UIApplicationStateInactive) || application.applicationState == UIApplicationStateBackground) {
        if ([HJUserManager isLogin] ) {
            if (![[userInfo allKeys] containsObject:@""]) {
                HJTabBarViewController *tabBarVC = (HJTabBarViewController *)self.window.rootViewController;
                HJChatRoomVC *vc = [self chatRoomDict:model];
                [tabBarVC.tabBarController.selectedViewController pushViewController:vc animated:YES];
            }
        }
    }
    //app在前台
    if (application.applicationState == UIApplicationStateActive ) {
        if (model.custom_content.pushType ==1) {
            LKLog(@"用户类推送");
        }else if (model.custom_content.pushType == 2) {
            LKLog(@"行程喜欢推送");
            [mNotificationCenter postNotificationName:NotificationReceiveLiveEachOtherBaiduPush object:nil userInfo:userInfo];
        }
    }
   
    [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:RCKitDispatchMessageNotification];
}

-(HJChatRoomVC *)chatRoomDict:(HJPushModel *)model {
    HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil] instantiateViewControllerWithIdentifier:chatRoom];
    RCConversationModel * conversationModel = [[RCConversationModel alloc]init];
    conversationModel.conversationTitle = model.custom_content.nickName;
    conversationModel.conversationType = ConversationType_PRIVATE;
    conversationModel.targetId = model.custom_content.userId;
    chatRoomVC.conversationModel = conversationModel;
    
    return chatRoomVC;
}

@end
